﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using BLL;
using MainApp.Helper;
using Model;
using System.Drawing.Imaging;
using System.IO;

namespace MainApp.Forms
{
    public partial class FormPerson : DevExpress.XtraEditors.XtraForm, IChildForm
    {
        DataContext context = new DataContext();
        FormAreaSelector areaSelector = new FormAreaSelector();
        string currentPhotoFilepath = null;
        string needDeletePhoto = null;
        bool isInsert = true;
        bool imageChanged = false;
        Person person = null;

        public FormPerson()
        {
            InitializeComponent();
            loadData();
        }

        public DialogResult ShowDialog(Person person, DataContext context)
        {
            this.person = person;
            this.context = context;
            isInsert = false;
            this.Text = "编辑人员信息";
            initData();
            return this.ShowDialog();
        }

        private void loadData()
        {
            this.nationBindingSource.DataSource = context.DataRepertory.Nations.ToList();
            this.professionBindingSource.DataSource = context.DataRepertory.Professions.ToList();
            this.politicalStatusBindingSource.DataSource = context.DataRepertory.PoliticalStatuses.ToList();
            this.relationBindingSource.DataSource = context.DataRepertory.Relations.ToList();
            this.personBindingSource.DataSource = context.DataRepertory.Persons.ToList();
        }

        private void initData()
        {
            this.txtName.Text = person.Name;
            this.txtAddress.Text = person.Address;
            this.txtAge.Text = DateTime.Now.Year - person.Birthday.Year + "";
            this.txtRemark.Text = person.Remark;
            this.lueMaster.EditValue = person.MasterID;
            this.lueNation.EditValue = person.NationID;
            this.luePoliticalStatus.EditValue = person.PoliticalStatusID;
            this.lueProfession.EditValue = person.ProfessionID;
            this.lueRelation.EditValue = person.RelationID;
            this.chkAlive.EditValue = person.IsAlive;
            this.chkArmyFamily.EditValue = person.IsArmyFamily;
            this.chkIsMaster.EditValue = person.IsHead;
            this.radSex.SelectedIndex = person.Sex == SexEnum.Male ? 0 : 1;
            this.dateEdit1.EditValue = person.Birthday;
            this.btnArea.Tag = person.Area;
            this.btnArea.Text = person.Area.FullPathName;
            this.txtPIN.Text = person.PIN;
            this.picture.EditValueChanged -= this.picture_EditValueChanged;
            if (string.IsNullOrEmpty(person.PhotoURI))
            {
                this.picture.Image = null;
            }
            else
            {
                try
                {
                    this.picture.Image = Image.FromFile(Program.AppConfig.PhotoRootPath + person.PhotoURI);
                }
                catch (Exception ex)
                {
                    Program.ShowMessage("照片加载出错，可能文件不存在！");
                    this.picture.Image = null;
                }
            }
            this.picture.EditValueChanged += this.picture_EditValueChanged;
        }

        private void resetForm()
        {
            this.txtName.Text = "";
            this.txtAddress.Text = "";
            this.txtAge.Text = "";
            this.txtRemark.Text = "";
            this.lueMaster.EditValue = null;
            this.lueNation.EditValue = null;
            this.luePoliticalStatus.EditValue = null;
            this.lueProfession.EditValue = null;
            this.lueRelation.EditValue = null;
            this.chkAlive.EditValue = true;
            this.chkArmyFamily.EditValue = false;
            this.chkIsMaster.EditValue = false;
            this.radSex.SelectedIndex = 0;
            this.dateEdit1.EditValue = DateTime.Now;
            this.btnArea.Tag = null;
            this.btnArea.Text = "";
            this.txtPIN.Text = "";
            this.picture.EditValueChanged -= this.picture_EditValueChanged;
            this.picture.Image = null;
            this.picture.EditValueChanged += this.picture_EditValueChanged;
            currentPhotoFilepath = null;
            needDeletePhoto = null;
        }

        private void btnArea_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            var dialogResult = areaSelector.ShowDialog();
            if (dialogResult == DialogResult.OK)
            {
                var area = areaSelector.GetSelectedArea();
                this.btnArea.Tag = area;
                this.btnArea.Text = area.FullPathName;
            }
        }

        public View.OperationResult Save()
        {
            throw new NotImplementedException();
        }

        public View.OperationResult Delete()
        {
            throw new NotImplementedException();
        }

        public View.OperationResult RefreshData()
        {
            areaSelector = new FormAreaSelector();
            return new View.OperationResult(true);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!dxValidationProvider1.Validate())
            {
                return;
            }
            if (isInsert)
            {
                person = new Person();
                context.DataRepertory.Persons.Add(person);
            }

            person.Address = this.txtAddress.Text;
            person.AreaID = ((Area)this.btnArea.Tag).ID;
            person.Birthday = this.dateEdit1.DateTime;
            person.IsAlive = this.chkAlive.Checked;
            person.IsHead = chkIsMaster.Checked;
            person.IsArmyFamily = chkArmyFamily.Checked;
            person.IsWBH = chkWBH.Checked;
            person.Sex = radSex.SelectedIndex == 0 ? SexEnum.Male : SexEnum.Female;
            if (!person.IsHead)
            {
                person.MasterID = (long)this.lueMaster.EditValue;
                person.RelationID = (long)this.lueRelation.EditValue;
            }
            person.Name = this.txtName.Text;
            person.NationID = (long)this.lueNation.EditValue;
            person.ProfessionID = (long)this.lueProfession.EditValue;
            person.PoliticalStatusID = (long)this.luePoliticalStatus.EditValue;
            person.PIN = this.txtPIN.Text;
            if (!string.IsNullOrEmpty(currentPhotoFilepath))
            {
                if (!string.IsNullOrEmpty(person.PhotoURI))
                {
                    needDeletePhoto = person.PhotoURI;
                }
                person.PhotoURI = currentPhotoFilepath;
            }
            else if (this.btnEditPic.Image == null && !string.IsNullOrEmpty(person.PhotoURI))//没有照片
            {
                needDeletePhoto = person.PhotoURI; person.PhotoURI = "";
            }

            var validateResult = context.DataRepertory.GetValidationErrors();
            if (validateResult.Count() > 0)
            {
                List<string> message = new List<string>();
                validateResult.ToList().ForEach(x =>
                {
                    if (!x.IsValid)
                    {
                        x.ValidationErrors.ToList().ForEach(f =>
                        {
                            message.Add(f.PropertyName + " " + f.ErrorMessage);
                        });
                    }
                });
                Program.ShowMessageDialog(message); return;
            }

            try
            {
                context.SaveChanges();
                if (needDeletePhoto != null)//删除旧的照片
                {
                    try
                    {
                        File.Delete(Program.AppConfig.PhotoRootPath + needDeletePhoto);
                    }
                    catch (Exception ex)
                    {
                        Program.ShowMessageDialog("删除原照片时出错，照片文件名：" + needDeletePhoto);
                    }
                }

                try
                {
                    if (currentPhotoFilepath != null)
                    {
                        this.picture.Image.Save(Program.AppConfig.PhotoRootPath + currentPhotoFilepath, ImageFormat.Png);
                    }
                }
                catch (Exception ex)
                {
                    Program.ShowMessageDialog("保存照片时出错！", ex.Message, ex.StackTrace);
                }
                Program.ShowMessage("数据已保存！");
                this.DialogResult = DialogResult.OK;
            }
            catch (Exception ex)
            {
                Program.ShowMessageDialog("保存数据时出错！", ex.Message, ex.StackTrace);
            }
        }

        private void chkIsMaster_CheckedChanged(object sender, EventArgs e)
        {
            this.lueMaster.Enabled = !chkIsMaster.Checked;
            this.lueRelation.Enabled = !chkIsMaster.Checked;
        }

        private void btnEditPic_Click(object sender, EventArgs e)
        {
            this.picture.LoadImage();
        }

        private void dateEdit1_EditValueChanged(object sender, EventArgs e)
        {
            if (this.dateEdit1.EditValue != null)
            {
                this.txtAge.EditValue = DateTime.Now.Year - this.dateEdit1.DateTime.Year + 1;
            }
        }

        private void picture_EditValueChanged(object sender, EventArgs e)
        {
            if (this.picture.Image != null)
            {
                currentPhotoFilepath = Guid.NewGuid().ToString() + ".png";
            }
            else
            {
                currentPhotoFilepath = null;
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnSaveContinue_Click(object sender, EventArgs e)
        {
            btnSave_Click(null, null);
            person = null;
            resetForm();
        }
    }
}